// 初始化分类树
function initCategoryTree(categories, selectedCategories = []) {
    const container = document.getElementById('categoryTreeContainer');
    container.innerHTML = ''; // 清空容器

    // 递归渲染节点
    function renderNode(node, level = 0) {
        const li = document.createElement('li');
        li.className = 'category-node';

        // 节点内容
        const div = document.createElement('div');
        div.className = 'form-check';
        div.style.paddingLeft = `${level * 20}px`; // 层级缩进

        // 复选框
        const checkbox = document.createElement('input');
        checkbox.type = 'checkbox';
        checkbox.className = 'form-check-input category-checkbox';
        checkbox.name = 'categories';
        checkbox.value = node.id;
        checkbox.id = `cat-${node.id}`;

         // 如果当前分类在已选列表中，则默认勾选
        if (selectedCategories.some(cat => cat.id === node.id)) {
            checkbox.checked = true;
        }

         // 如果当前分类或其任意子分类被选中，则展开
        // const shouldExpand = selectedCategories.some(cat =>
        //     cat.id === node.id ||
        //     (node.children && node.children.some(child =>
        //         selectedCategories.some(c => c.id === child.id)
        //     )
        // ))
        //
        // if (shouldExpand) {
        //     li.querySelector('.children').style.display = 'block';
        //     li.querySelector('.bi-caret-down-fill').classList.remove('bi-caret-right-fill');
        //     li.querySelector('.bi-caret-down-fill').classList.add('bi-caret-down-fill');
        // }

        // 标签
        const label = document.createElement('label');
        label.className = 'form-check-label ms-2';
        label.htmlFor = `cat-${node.id}`;

        // 图标（根据是否有子节点）
        const icon = document.createElement('i');
        icon.className = node.children && node.children.length > 0 ?
            // 'bi bi-folder me-1' : 'bi bi-circle me-1';
            'bi-caret-down-fill text-primary' : 'bi bi-folder-fill me-1 text-primary';

        label.appendChild(icon);
        label.appendChild(document.createTextNode(node.name));

        div.appendChild(checkbox);
        div.appendChild(label);
        li.appendChild(div);

        // 复选框添加事件阻止
        checkbox.addEventListener('click', function(e) {
          e.stopPropagation(); // 阻止事件冒泡
        });

        // 标签添加事件阻止
        label.addEventListener('click', function(e) {
          e.stopPropagation(); // 阻止事件冒泡
        });

        // 递归子节点
        if (node.children && node.children.length > 0) {
            const childContainer = document.createElement('ul');
            childContainer.className = 'children ps-0';
            node.children.forEach(child => {
                childContainer.appendChild(renderNode(child, level + 1));
            });
            li.appendChild(childContainer);
        }

        return li;
    }

    // 渲染所有根节点
    categories.forEach(root => {
        container.appendChild(renderNode(root));
    });

    // 更新已选分类显示
    updateSelectedDisplay();

    // 添加事件监听
    setupCategoryEvents();

}

// 设置分类选择事件
function setupCategoryEvents() {
    const container = document.getElementById('categoryTreeContainer');

    // 点击事件委托
    container.addEventListener('change', function(e) {
        if (e.target.classList.contains('category-checkbox')) {
            updateSelectedDisplay();
        }
    });
}

// 更新已选分类显示
// function updateSelectedDisplay() {
//     const selected = [];
//     document.querySelectorAll('.category-checkbox:checked').forEach(checkbox => {
//         const label = checkbox.nextElementSibling;
//         selected.push(label.textContent.trim());
//     });
//
//     document.getElementById('selectedCategories').textContent =
//         selected.length ? `已选: ${selected.join('、')}` : '未选择分类';
// }
function updateSelectedDisplay() {
    const selected = [];
    document.querySelectorAll('.category-checkbox:checked').forEach(checkbox => {
        const label = checkbox.nextElementSibling;
        selected.push({
            id: parseInt(checkbox.value),
            name: label.textContent.trim()
        });
    });

    // 显示已选分类（兼容纯文本或对象格式）
    const displayText = selected.map(cat =>
        typeof cat === 'object' ? cat.name : cat
    ).join('、');

    document.getElementById('selectedCategories').textContent =
        selected.length ? `已选: ${displayText}` : '未选择分类';
}